package cn.stronglink.assetmanage.business.login;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnCheckedChanged;
import butterknife.OnClick;
import butterknife.Unbinder;
import cn.stronglink.assetmanage.R;
import cn.stronglink.assetmanage.business.task.TaskActivity;
import cn.stronglink.assetmanage.dao.DaoManager;
import cn.stronglink.assetmanage.dao.UserDao;
import cn.stronglink.assetmanage.entity.User;
import cn.stronglink.assetmanage.entity.UserOnLine;
import cn.stronglink.assetmanage.utils.APKVersionCodeUtils;
import cn.stronglink.assetmanage.utils.LogUtil;
import cn.stronglink.assetmanage.utils.MD5Encrypt;
import cn.stronglink.assetmanage.utils.PrefUtils;
import cn.stronglink.assetmanage.utils.ToastUtil;
import cn.stronglink.assetmanage.widget.CustomProgressDialog;
import cn.stronglink.netrequest.business.base.BaseDataService;
import cn.stronglink.netrequest.business.user.LoginService;
import cn.stronglink.netrequest.util.HttpURL;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class LoginActivity extends Activity {
    @BindView(R.id.et_user_name)
    EditText etUserName;
    @BindView(R.id.et_pwd)
    EditText etPwd;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.cb_remPwd)
    CheckBox cbRemPwd;
    @BindView(R.id.rg_login)
    RadioGroup rgLogin;
    @BindView(R.id.rb_local)
    RadioButton rbLocal;
    @BindView(R.id.rb_online)
    RadioButton rbOnline;
    @BindView(R.id.tv_app_code_name)
    TextView tvAppCodeName;
    private static final String KEY_USERNAME = "userName", KEY_PASSWORD = "userPassword",
            REM_PASSWORD ="remberPwd";
    LoginService service;
    Dialog mDialog;
    private Gson gson = new Gson();
    private Unbinder mUnbinder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        initViewAndData();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mUnbinder.unbind();
    }

    private void initViewAndData() {
        mUnbinder = ButterKnife.bind(this);
        service = new LoginService();
        mDialog = CustomProgressDialog.createLoadingDialog(this, "正在加载中...");
        mDialog.setCancelable(false);
        if (DaoManager.getDaoSession(getApplicationContext()).getServerIpDao().queryBuilder().count() > 0) {
            HttpURL.setNewHost(DaoManager.getDaoSession(getApplicationContext()).getServerIpDao().queryBuilder().unique().getIpAddress());
        }
        showUserInfo();
        tvAppCodeName.setText("v" + APKVersionCodeUtils.getVerName(this));

        rgLogin.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(rbLocal.getId()==checkedId){
                    rbLocal.setTextColor(getResources().getColor(R.color.rb_text_choose_color));
                    rbOnline.setTextColor(getResources().getColor(R.color.rb_text_color));
                }
                if (rbOnline.getId()==checkedId){
                    rbLocal.setTextColor(getResources().getColor(R.color.rb_text_color));
                    rbOnline.setTextColor(getResources().getColor(R.color.rb_text_choose_color));
                }
            }
        });
    }

    private void showUserInfo() {
        etUserName.setText(PrefUtils.getString(KEY_USERNAME, "", this));
        boolean isCheck = PrefUtils.getBoolean(REM_PASSWORD, true, this);
        cbRemPwd.setChecked(isCheck);
        if (isCheck) {
            etPwd.setText(PrefUtils.getString(KEY_PASSWORD, "", this));
        } else {
            etPwd.setText("");
        }
        cbRemPwd.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                PrefUtils.putBoolean(REM_PASSWORD, isChecked, LoginActivity.this);
            }
        });
    }

    @OnClick(R.id.btn_login)
    public void login() {
        judgeUserInfo();
    }


    private void judgeUserInfo() {
        if ("".equals(etUserName.getText().toString())) {
            ToastUtil.toastShort("用户名不能为空!");
            return;
        }
        if ("".equals(etPwd.getText().toString())) {
            ToastUtil.toastShort("密码不能为空!");
            return;
        }
        //登录
        loginUserInfo();
    }

    /**
     * 登录
     */
    private void loginUserInfo() {
        if ("admin".equals(etUserName.getText().toString()) && "admin87654321".equals(etPwd.getText().toString())) {
            User user = User.getInstance();
            user.setAccount("admin");
            user.setName("admin");
            Intent intent = new Intent(LoginActivity.this, TaskActivity.class);
            this.startActivity(intent);
            finish();
            return;
        }
        if (null != service) {
            if (rbOnline.isChecked()) {
                onlineLogin();
            } else {
                localLogin();
            }
        }
    }

    /**
     * 在线登录
     */
    private void onlineLogin() {
        try {
            mDialog.show();
            service.login(etUserName.getText().toString(), etPwd.getText().toString(), new Callback() {
                @Override
                public void onFailure(@NonNull Call request, @NonNull IOException e) {
                    mDialog.cancel();
                    ToastUtil.toastShort("抱歉,登陆失败!");
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    mDialog.cancel();
                    String json = response.body().string();
                    UserOnLine result = null;
                    result = gson.fromJson(json, new TypeToken<UserOnLine>() {
                    }.getType());
                    if (result != null && result.getHttpCode() == HttpURLConnection.HTTP_OK) {
                        ToastUtil.toastShort("登陆成功!");
                        User user = User.getInstance();
                        user.setAccount(result.getUser().getAccount());
                        user.setName(result.getUser().getName());
                        user.setId_(result.getUser().getId_());
                        PrefUtils.putString(KEY_USERNAME, etUserName.getText().toString(), LoginActivity.this);
                        PrefUtils.putString(KEY_PASSWORD, etPwd.getText().toString(), LoginActivity.this);
                        DaoManager.getDaoSession(LoginActivity.this).getUserDao().insertOrReplace(user);
                        jumpActivity();
                    } else {
                        ToastUtil.toastShort("登陆失败!");
                    }
                }
            });
        } catch (Exception e) {
            ToastUtil.toastShort("请稍后重试!");
            mDialog.cancel();
        }
    }

    /**
     * 本地登录
     */
    private void localLogin() {
        String userName = etUserName.getText().toString();
        List<User> userList = DaoManager.getDaoSession(LoginActivity.this).getUserDao().queryBuilder().where(UserDao.Properties.Account.eq(userName)).list();
        if (null != userList && userList.size() > 0) {
            if (MD5Encrypt.encrypt(etPwd.getText().toString()).equals(userList.get(0).getPassword())) {
                User user = User.getInstance();
                user.setId_(userList.get(0).getId_());
                user.setAccount(userList.get(0).getAccount());
                user.setPassword(userList.get(0).getPassword());
                user.setName(userList.get(0).getName());
                PrefUtils.putString(KEY_USERNAME, userName, LoginActivity.this);
                PrefUtils.putString(KEY_PASSWORD, etPwd.getText().toString(), LoginActivity.this);
                jumpActivity();
            } else {
                ToastUtil.toastShort("密码错误!");
            }
        } else {
            ToastUtil.toastShort("用户不存在!");
        }
    }

    private void jumpActivity() {
        Intent intent = new Intent(LoginActivity.this, TaskActivity.class);
        startActivity(intent);
        finish();
    }

}
